//
//  fileDownloader.m
//  03-大文件下载
//
//  Created by 王禹丞 on 15/11/11.
//  Copyright © 2015年 WYC. All rights reserved.
//

#import "FileDownloader.h"

@interface FileDownloader()<NSURLConnectionDataDelegate>

@property (nonatomic,strong) NSURLConnection *conn;

@property (nonatomic,strong)NSFileHandle * writeHandle;

@property (nonatomic,assign) long long currentLength;

@property (nonatomic,assign) long long totalLength;

@property (nonatomic,strong)dispatch_queue_t writeQueue;

@property (nonatomic,strong)NSOperationQueue *queue;

@end


@implementation FileDownloader


- (void)start{

    
    NSURL *url = [NSURL URLWithString:self.url];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSString *value = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
    
    [request setValue:value forHTTPHeaderField:@"Range"];
    
    self.conn = [NSURLConnection connectionWithRequest:request delegate:self];

    _downloading = YES;
}

- (void)pause{

    [self.conn cancel];

    self.conn = nil;

    _downloading = NO;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    
    if (self.failureHandler) {
        
        self.failureHandler (error);
    }
    
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    
    if (self.totalLength) {
        
        return;
    }
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    // 刚创建完毕的大小是0字节
    [mgr createFileAtPath:self.destPath contents:nil attributes:nil];

    
    self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
    
    self.totalLength = response.expectedContentLength;
    
   // self.writeQueue = dispatch_queue_create("wyc", NULL);
    
   // self.queue = [[NSOperationQueue alloc]init];
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    
    NSLog(@"didReceiveData");
    
    self.currentLength += data.length;

    
    double progress =(double) self.currentLength / self.totalLength;
 
    
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        
        if (self.progressHandler) {
            
            self.progressHandler(progress);
            
        }
        
    });

    
    
//    
//    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
    
        [self.writeHandle seekToEndOfFile];
        
        [self.writeHandle writeData:data];
        
    
//    }];

//    NSOperation *lastOperation = [self.queue.operations lastObject];
//    
//    if (lastOperation) {
//        
//        [operation addDependency:lastOperation];
//    }
//    
//    [self.queue addOperation:operation];
//    
    
//    dispatch_async(self.writeQueue, ^{
//        
//     
//    });
    
   
    
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    
    
    self.currentLength = 0;
    
    self.totalLength= 0;
    
    if (self.currentLength == self.totalLength) {
        
        [self.writeHandle closeFile];
        
        self.writeHandle = nil;
        
    }
    

    if (self.completionHandler) {
    
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.progressHandler) {
                
                self.completionHandler();
                
            }
            
        });
        

        
    }
}


@end
